<?php
class AuthController extends Controller {

    public $defaultAction = 'login';
    public $recoveryUrl;
    
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('login', 'merchantlogin', 'recovery', 'setnewpassword', 'register', 'activate','resetactivation'),
                'users' => array('?'), //anonymous user
            ),
            array('allow',
                'actions' => array('logout'),
                'users' => array('@'),
            ),
            array('allow',
                'actions'=>array('captcha'),
                'users'=>array('*'),
            ),
//            array('deny',
//                'actions'=> array('login', 'recovery', 'register', 'activate'),
//                'users'=>array('@'),
//                //'deniedCallback'=>Yii::app()->user->isGuest?null:$this->redirect(Yii::app()->user->returnUrl),
//                //'deniedCallback'=>$this->redirect('/'),
//                //'deniedCallback'=>function(){ Yii::app()->controller->redirect(array('/controller/action')); },
//            ),
            array('deny'),
        );
    }

    public function actions() {
        return array(
            'captcha' => array(
                'class' => 'ext.widgets.captchaExtended.CaptchaExtendedAction',
                'mode' => $this->captchaMode,
            ),
        );
    }

    public function init() {
        parent::init();

    }

    public function actionLogin() {
        
        $model = new User('login');
        $this->performAjaxValidation($model);        
        Yii::app()->user->recordUrlReferrer();

        $params = Yii::app()->request->getParam(get_class($model));
        if ($params) {
            $model->attributes=$params;
            if ($model->validate()) {
                $identity = new UserIdentity($model->username_, $model->password_);
                if($identity->authenticate()){                    
                    Yii::app()->user->login($identity, $model->rememberMe_? Yii::app()->params['cookieLoginDuration']:0); // cookie-based login 7 days
                    $user=Yii::app()->user->loadModel();
                    $user->updateLoginTime();
                    Yii::app()->setLanguage($user->preferredLanguageCode);
                    $this->redirect(Yii::app()->user->returnUrl);
                }else{
                    $model->addError('error', $identity->getErrorMessage());
                }
            }//end if
        }//end if else

        $this->recoveryUrl=$this->createUrl('recovery');
        $this->render('loginForm', array(
            'model' => $model,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'focus' => array($model, 'username_'),
            ),
        ));
    }

    public function actionMerchantlogin() {
        
        $model = new User('login');
        $this->performAjaxValidation($model);
        Yii::app()->user->recordUrlReferrer();

        $params = Yii::app()->request->getParam(get_class($model));
        if ($params) {
            $model->attributes=$params;
            if ($model->validate()) {
                $identity = new UserIdentity($model->username_, $model->password_);
                if($identity->authenticate(UserIdentity::MERCHANT)){
                    Yii::app()->user->login($identity, $model->rememberMe_? Yii::app()->params['cookieLoginDuration']:0); // cookie-based login 7 days
                    $user=Yii::app()->user->loadModel();
                    $user->updateLoginTime();
                    Yii::app()->setLanguage($user->preferredLanguageCode);                    
                    $this->redirect(Yii::app()->user->returnUrl);
                }else{
                    $model->addError('error', $identity->getErrorMessage());
                }
            }//end if
        }//end if else

        $this->recoveryUrl=$this->createUrl('recovery');
        $this->render('merchantLoginForm', array(
            'model' => $model,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'focus' => array($model, 'username_'),
            ),
        ));
    }
    
    /**
     * Recovery
     */
    public function actionRecovery() {

        $model = new User('recovery');
        $this->performAjaxValidation($model);

        $params = Yii::app()->request->getParam(get_class($model));
        if ($params) {
            $model->attributes=$params;
            if ($model->validate()) {
                $user=$model->accessible()->withEmail($model->email_)->find();
                if (empty($user)) {
                    $model->addError('error', Lang::t('user.recovery.flash.email.not.found'));
                }else{             
                    $email = new Email;
                    $email->to = array($user->email => $user->name);
                    $email->params = array('user' => $user);
                    $email->subject = Lang::t('user.recovery.mail.notify.user.subject');
                    $email->view = 'user.passwordRecovery';
                    if ($email->send()) {
                        Yii::app()->response->type(WebResponse::PASSWORD_RECOVERY_SUCCESS);
                    } else {
                        Yii::app()->response->type(WebResponse::PASSWORD_RECOVERY_FAIL);
                    }//end if else
                }//end if
            }//end if
        }//end if else

        $this->render('recoveryForm', array(
            'model' => $model,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'focus' => array($model, 'email_'),
            ),
        ));
    }

    public function actionSetnewpassword($a=null, $k=null){
        
        if(empty($a) || empty($k)) HttpStatus::code(404);
        
        $model=User::model()->findByValidationCode($k);
        if(empty($model)) HttpStatus::code(404);
        
        if($model->isResetPasswordCodeExpired){
            Yii::app()->response->type(WebResponse::PASSWORD_RECOVERY_URL_EXPIRED);
        }
        
        $model->scenario='setNewPassword';
        $this->performAjaxValidation($model);

        $params = Yii::app()->request->getParam(get_class($model));
        if($params){
            $model->attributes=$params;
            if($model->validate()){
                if($model->updatePassword()){
                    Yii::app()->response->type(WebResponse::PASSWORD_RECOVERY_URL_SUCCESS);
                }
            }
        }
        
        $this->render('setNewPasswordForm',array(
            'model' => $model,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'focus' => array($model, 'password_'),
            ),
        ));
    }
    
    public function actionRegister() {

        $model = new User('userRegister');
        $model->autoFill();
        $address=new Address;
        $address->autoFill($model);
        $this->performAjaxValidation($model,$address);

        $params = Yii::app()->request->getParam(get_class($model));
        //$addressParams = Yii::app()->request->getParam(get_class($address));
        if ($params) {
        //if ($params && $addressParams) {
            $model->attributes=$params;
            $model->country_=$address->country_;
            $model->validate();
            //$address->attributes=$addressParams;
            //$address->validate();
            if (!$model->hasErrors() && $model->addRecord($address)) {
            //if (!$model->hasErrors() && !$address->hasErrors() && $model->addRecord($address)) {
                Yii::app()->setLanguage($model->preferredLanguageCode);
                if (Yii::app()->params['userOptInMode']) {
                    $email = new Email;
                    $email->to = array($model->email => $model->name);
                    $email->params = array('user' => $model);
                    $email->subject = Lang::t('user.register.mail.notify.user.subject', array('{domainname}' => Yii::app()->request->hostInfo));
                    $email->view = 'user.registerWelcomeNote';
                    $subject=$email->send();
                }//end if
                Yii::app()->response->type(WebResponse::USER_REGISTER_SUCCESS);
            }//end if
        }//end if

        $this->render('registerForm', array(
            'user' => $model,
            'address'=>$address,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'focus' => array($model, 'firstName_'),
            ),
        ));
    }

    /**
     * activation
     */
    public function actionActivate() {

        $key = Yii::app()->request->getParam('k_');
        if (empty($key)) {
            HttpStatus::code(404);
        } else {
            $model = User::model()->findByActivationKey($key);
            if (empty($model)) {
                HttpStatus::code(400);
            } elseif ($model->statusCode == Option::STATUS_ACTIVE) {
                Yii::app()->response->type(WebResponse::USER_ACTIVATE_ACTIVATED);
            } elseif ($model->isVerificationCodeExpired) {
                Yii::app()->response->type(WebResponse::USER_ACTIVATE_EXPIRED, array(
                    'resetActivationCodeUrl' => $model->resetActivationCodeUrl,
                ));
            } elseif ($model->activateRecord()) {
                Yii::app()->response->type(WebResponse::USER_ACTIVATE_SUCCESS);
            } else {
                Yii::app()->response->type(WebResponse::USER_ACTIVATE_FAIL);
            }//end if else
        }//end if else
    }
    
    public function actionResetactivation() {

        $key = Yii::app()->request->getParam('k_');
        if (empty($key)) {
            HttpStatus::code(404);
        } else {
            $model = User::model()->findByActivationKey($key);
            if (empty($model)) {
                HttpStatus::code(400);
            } elseif ($model->resetActivationCode()) {
                $this->sendActivationEmail($model->id);
                Yii::app()->response->type(WebResponse::USER_REGISTER_RESET_ACTIVATION);
            } else {
                Yii::app()->response->type(WebResponse::USER_ACTIVATE_FAIL);
            }//end if else
        }//end if else
    }

    public function actionLogout($token=null) {
        if (empty($token) || $token !== Yii::app()->request->csrfToken) {
            HttpStatus::code(400);
        }

        Yii::app()->user->logout();
        Yii::app()->user->clearStates();
        Yii::app()->session->clear();
        Yii::app()->session->destroy();
        $this->redirect(Yii::app()->request->urlReferrer);
    }

}//end class